package adapter.group_management;

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;
import define.API;
import model.group_management.GroupManagementItem;
import model.user_management.AllTabInUserManagementItem;
import ui.fragment.group_management.AddMemberToGroupFragment;
import ui.fragment.group_management.GroupFeedFragment;
import ui.fragment.user_management.AllTabInUserManagementFragment;


/**
 * Created by trek2000 on 21/8/2014.
 */
public class AddMemberToGroupAdapter extends BaseAdapter {

    /**
     * Data section
     */
    private ArrayList <AllTabInUserManagementItem> mAlAllTabInUserManagement = new ArrayList<>();

    /**
     * Interface section
     */

    /**
     * String section
     */
    private int textViewResourceId;
    private int pos_of_checked_item = -1;
    public static ArrayList <Integer> mAlPosOfItemCheckedInAddMemberToGroup =  new ArrayList<>();
    public static ArrayList <Integer> mAlPosOfItemCheckedInAddGroupManager =  new ArrayList<>();
    private Boolean IS_ADD_GROUP_MANAGER = false;
    /**
     * The other section
     */
    private Context mContext;
    private DisplayImageOptions mDio;
    private ViewHolder viewHolder;

    private class ViewHolder {
        private CircleImageView circleIvItem;
        private TextView mTvUserName;
        private TextView mTvRole;
        private CheckBox mCbItem;
    }

    /**
     * @param context
     */
    public AddMemberToGroupAdapter(Context context, int textViewResourceId,
                                   ArrayList <AllTabInUserManagementItem> mAlallTabInUserManagement,
                                   boolean is_add_group_manager) {
        this.mContext = context;
        this.textViewResourceId = textViewResourceId;
        this.mAlAllTabInUserManagement = mAlallTabInUserManagement;
        this.IS_ADD_GROUP_MANAGER = is_add_group_manager;

        mDio = new DisplayImageOptions.Builder()
                .delayBeforeLoading(1000)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    /**
     * @return
     */
    public int getCount() {
        return mAlAllTabInUserManagement.size();
    }

    /**
     * @param position
     * @return
     */
    public AllTabInUserManagementItem getItem(int position) {
        return mAlAllTabInUserManagement.get(position);
    }

    /**
     * @param position
     * @return
     */
    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(final int pos, View convertView, ViewGroup parent) {
        //clear mAlPosOfItemCheckedInAddGroupManager and mAlPosOfItemCheckedInAddMemberToGroup
        //because is Al public so it not initialize again
//        if (!mAlPosOfItemCheckedInAddGroupManager.isEmpty()) {
//            mAlPosOfItemCheckedInAddGroupManager.clear();
//        }
//        if (!mAlPosOfItemCheckedInAddMemberToGroup.isEmpty()) {
//            mAlPosOfItemCheckedInAddMemberToGroup.clear();
//        }
        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(textViewResourceId, null);
            viewHolder.circleIvItem = (CircleImageView) convertView.findViewById(R.id.circleiv_item_in_simple_list_item_in_add_member_to_group_fragment);
            viewHolder.mTvUserName = (TextView) convertView.findViewById(R.id.tv_user_name_in_simple_list_item_in_add_member_to_group_fragment);
            viewHolder.mTvRole = (TextView) convertView.findViewById(R.id.tv_role_in_simple_list_item_in_add_member_to_group_fragment);
            viewHolder.mCbItem = (CheckBox) convertView.findViewById(R.id.cb_item_in_simple_list_item_in_add_member_to_group_fragment);

            viewHolder.circleIvItem.setTag(pos);
            viewHolder.mTvUserName.setTag(pos);
            viewHolder.mTvRole.setTag(pos);
            viewHolder.mCbItem.setTag(pos);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder)convertView.getTag();

            viewHolder.circleIvItem.setTag(pos);
            viewHolder.mTvUserName.setTag(pos);
            viewHolder.mTvRole.setTag(pos);
            viewHolder.mCbItem.setTag(pos);
        }
        //set data
        try {
            String URL = "";
            if (API.IS_DEV_SITE)
                URL = mAlAllTabInUserManagement.get(pos).getAvatar().replace("https", "http");
            else
                URL = mAlAllTabInUserManagement.get(pos).getAvatar();

            Enterprise.imageLoader.displayImage(
                    URL,
                    viewHolder.circleIvItem, mDio,
                    new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingStarted(String imageUri, View view) {
                        }

                        @Override
                        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        }

                        @Override
                        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                            if (loadedImage != null & view.findViewWithTag(pos) != null) {
                                ((ImageView) view.findViewWithTag(pos)).setImageBitmap(loadedImage);
                            }
                        }
                    }, new ImageLoadingProgressListener() {
                        @Override
                        public void onProgressUpdate(
                                String imageUri, View view, int current, int total) {
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
        viewHolder.mTvUserName.setText(mAlAllTabInUserManagement.get(pos).getFirstName() + " " +
                mAlAllTabInUserManagement.get(pos).getLastName());
        viewHolder.mTvRole.setText(mAlAllTabInUserManagement.get(pos).getRole());

        if (IS_ADD_GROUP_MANAGER) {
            //reset view case:  add group manager, only choose one user.
            if (pos == pos_of_checked_item)
                ((CheckBox) viewHolder.mCbItem.findViewWithTag(pos)).setChecked(true);
            else
                ((CheckBox) viewHolder.mCbItem.findViewWithTag(pos)).setChecked(false);

        } else {
            //  //reset view case:  add member to group, can choose many users
            // reset all item is false, after set is checked items in mAlPosOfItemCheckedInAddMemberToGroup
            ((CheckBox) viewHolder.mCbItem.findViewWithTag(pos)).setChecked(false);
            if (mAlPosOfItemCheckedInAddMemberToGroup.size() > 0) {
                for (int c = 0 ; c < mAlPosOfItemCheckedInAddMemberToGroup.size(); c++) {
                    if (pos == mAlPosOfItemCheckedInAddMemberToGroup.get(c))
                        ((CheckBox) viewHolder.mCbItem.findViewWithTag(pos)).setChecked(true);
                }
            }
        }
        // on click listener
        viewHolder.mCbItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean checked = ((CheckBox)v).isChecked();
                switch (v.getId()) {
                    case R.id.cb_item_in_simple_list_item_in_add_member_to_group_fragment:
                        if (checked) {
                            if (IS_ADD_GROUP_MANAGER) {
                                //case add group manager: only choose one item
                                //reset view
                                pos_of_checked_item = pos;
                                AddMemberToGroupFragment.addMemberToGroupAdapter.notifyDataSetChanged();
                                //add item to single ton
                                if (!mAlPosOfItemCheckedInAddGroupManager.isEmpty()) {
                                    mAlPosOfItemCheckedInAddGroupManager.clear();
                                }
                                mAlPosOfItemCheckedInAddGroupManager.add(pos);
//                                Enterprise.groupManagement.setmAlPosOfItemCheckedInAddGroupManager(mAlPosOfItemCheckedInAddGroupManager);
                                // set text for text view add
                                AddMemberToGroupFragment.setTextForTextViewAddInAddMemberToGroupFragment(mAlPosOfItemCheckedInAddGroupManager,
                                        IS_ADD_GROUP_MANAGER);
                            } else {
                                //case add member to group: can  choose many items
                                //reset view
                                AddMemberToGroupFragment.addMemberToGroupAdapter.notifyDataSetChanged();
                                //add item to single ton
                                mAlPosOfItemCheckedInAddMemberToGroup.add(pos);
//                                Enterprise.groupManagement.setmAlPosOfItemCheckedInAddMemberToGroup(mAlPosOfItemCheckedInAddMemberToGroup);
                                // set text for text view add
                                AddMemberToGroupFragment.setTextForTextViewAddInAddMemberToGroupFragment(mAlPosOfItemCheckedInAddMemberToGroup,
                                        IS_ADD_GROUP_MANAGER);
                            }
                        } else {
                            if (IS_ADD_GROUP_MANAGER) {
                                //case add group manager: only choose one item
                                //add item to single ton
                                if (!mAlPosOfItemCheckedInAddGroupManager.isEmpty()) {
                                    mAlPosOfItemCheckedInAddGroupManager.clear();
                                }
//                                Enterprise.groupManagement.setmAlPosOfItemCheckedInAddGroupManager(mAlPosOfItemCheckedInAddGroupManager);
                                // set text for text view add
                                AddMemberToGroupFragment.setTextForTextViewAddInAddMemberToGroupFragment(mAlPosOfItemCheckedInAddGroupManager,
                                        IS_ADD_GROUP_MANAGER);
                            } else {
                                //case add member to group: can  choose many items
                                //add item to single ton
                                for (int i = 0; i < mAlPosOfItemCheckedInAddMemberToGroup.size(); i++) {
                                    if (mAlPosOfItemCheckedInAddMemberToGroup.get(i) == pos ) {
                                        mAlPosOfItemCheckedInAddMemberToGroup.remove(i);
//                                        Enterprise.groupManagement.setmAlPosOfItemCheckedInAddMemberToGroup(mAlPosOfItemCheckedInAddMemberToGroup);
                                    }
                                }
                                // set text for text view add
                                AddMemberToGroupFragment.setTextForTextViewAddInAddMemberToGroupFragment(mAlPosOfItemCheckedInAddMemberToGroup,
                                        IS_ADD_GROUP_MANAGER);
                            }
                        }
                        break;
                }
            }
        });
        return convertView;
    }
}